package com.mexico.inloancash.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.widget.NestedScrollView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.appsflyer.AppsFlyerLib;
import com.mexico.inloancash.activity.IndiaAddBankActivity;
import com.mexico.inloancash.activity.IndiaBankInfoActivity;
import com.mexico.inloancash.activity.IndiaHomeActivity;
import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.activity.IndiaConfirm_LoanActivity;
import com.mexico.inloancash.activity.IndiaLoginActivity;
import com.mexico.inloancash.activity.IndiaRecommendationActivity;
import com.mexico.inloancash.activity.IndiaWebViewActivity;
import com.mexico.inloancash.activity.MainActivity;
import com.mexico.inloancash.bean.BaseBean;
import com.mexico.inloancash.bean.INdia_Update_CardInfoListBean;
import com.mexico.inloancash.bean.India_User_LoginList_Home_Bean;
import com.mexico.inloancash.bean.India_MessageInfo_ListBean;
import com.mexico.inloancash.bean.India_User_PhoneList_Bean;
import com.mexico.inloancash.bean.India_UnLogin_Home_ListBean;
import com.mexico.inloancash.bean.India_UrlListBean;
import com.mexico.inloancash.dialog.India_Update_BankNumber_Dialog;
import com.mexico.inloancash.dialog.India_User_Coupon_CommonDialog;
import com.mexico.inloancash.dialog.India_UserNotice_CommonDialog;
import com.mexico.inloancash.dialog.India_User_Reward_CommonDialog;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.india_interfacedai.IndiaDealDialogInterface;
import com.mexico.inloancash.india_interfacedai.IndiaOnDialogListener;
import com.mexico.inloancash.india_interfacedai.IndiaRewardDialogInterface;
import com.mexico.inloancash.utils.IndiaAdjust_Helper;
import com.mexico.inloancash.utils.DeviceIdUtil;
import com.mexico.inloancash.utils.India_FileApp_InstallUtil;
import com.mexico.inloancash.utils.IntentUtils;
import com.mexico.inloancash.utils.LocationTool;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;
import com.mexico.inloancash.utils.permission.RxPermissions;
import com.mexico.inloancash.utils.permission.SchedulerTransformer;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class IndiaFirstPageFragment extends BaseFragment implements IndiaDealDialogInterface, LocationTool.onBackLoCtion, IndiaRewardDialogInterface {

    @BindView(R.id.head_linear)
    LinearLayout mHeadLinear;

    @BindView(R.id.jinrong)
    ImageView mIndia_Jinrong;

    @BindView(R.id.limit)
    TextView mlimit;

    @BindView(R.id.quota)
    TextView quota;

    @BindView(R.id.first_bottom)
    Button mIndia_FirstBottom;

    /**
     * 首页
     */
    @BindView(R.id.first_join_card)
    LinearLayout mIndia_FirstJoinCard;

    @BindView(R.id.fangkuanhou_quota)
    TextView mIndia_FangkuanhouQuota;

    @BindView(R.id.fangkuanhou_date)
    TextView mIndia_FangkuanhouDate;

    @BindView(R.id.fangkuanhou_bottmom)
    Button mIndia_FangkuanhouBottmom;

    /**
     * 放款成功
     */
    @BindView(R.id.fangkuan_card)
    RelativeLayout mIndia_FangkuanCard;

    @BindView(R.id.shenhetongguo_card)
    RelativeLayout mIndia_ShenhetongguoCard;

    @BindView(R.id.shenhezhong_image)
    ImageView mIndia_ShenhezhongImage;

    @BindView(R.id.shenhezhong_card)
    RelativeLayout mIndia_ShenhezhongCard;

    @BindView(R.id.jujue_vip)
    LinearLayout mIndia_JujueVip;

    @BindView(R.id.jujue_pay)
    TextView mIndia_JujuePay;

    @BindView(R.id.jujue_line)
    TextView mIndia_JujueLine;

    @BindView(R.id.jujue_bottom)
    Button mIndia_JujueBottom;

    @BindView(R.id.shenhejujue_card)
    RelativeLayout mIndia_ShenhejujueCard;

    Unbinder unbinder;

    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    //    @BindView(R.id.loadView)
//    LoadingView loadView;
    @BindView(R.id.nestedScroll)
    NestedScrollView mIndia_NestedScroll;

    @BindView(R.id.jujuegg_botton)
    Button mIndia_JujueggBotton;

    @BindView(R.id.jujuegg_card)
    RelativeLayout mIndia_JujueggCard;

    @BindView(R.id.dengdai_image)
    ImageView mIndia_DengdaiImage;

    @BindView(R.id.dengdai_card)
    RelativeLayout mIndia_DengdaiCard;

    @BindView(R.id.huankuan_amount)
    TextView huankuan_amount;

    @BindView(R.id.huankuan_damount)
    TextView huankuan_damount;

    @BindView(R.id.huankuan_shuifei)
    TextView huankuan_shuifei;

    @BindView(R.id.huankuan_yongjin)
    TextView huankuan_yongjin;

    @BindView(R.id.huankuan_lilv)
    TextView huankuan_lilv;

    @BindView(R.id.shenghetongguo_amount)
    TextView shenghetongguo_amount;

    @BindView(R.id.shenghetongguo_damount)
    TextView shenghetongguo_damount;

    @BindView(R.id.shenghetongguo_shuifei)
    TextView shenghetongguo_shuifei;

    @BindView(R.id.shenghetongguo_yongjin)
    TextView shenghetongguo_yongjin;

    @BindView(R.id.shenghetongguo_lilv)
    TextView shenghetongguo_lilv;

    @BindView(R.id.shenghetongguo_date)
    TextView shenghetongguo_date;



    /*@BindView(R.id.tv_cons)
    TextView tv_cons;*/

    private View firstPage;
    private int authStatus = -1;//认证状态
    private String webUrl = "";//h5链接
    private String orderNo;//借款订单号
    private int status; //1代表审核拒绝，2代表待还款
    private String mDay, mDaozhang, mFuwu, mAllMount, mLixi, mZongshu;//分别代表多少天，到账多少，服务费，还多少，利息多少，总额度多少

    private String mDamount; // 到账金额
    private String mPayAmount; //应还款金额

    private India_UserNotice_CommonDialog dialog;
    private Handler handler = new Handler();
    private int commit = -1;
    private LocationTool tool;
    public static String location = "地址获取失败";
    public static String mLongitude="";
    public static String mLatitude="";
    private India_User_Reward_CommonDialog userRewardCommonDialog;
    private int one = -1;
    private boolean bank = false;

    private India_Update_BankNumber_Dialog updateBankNumberDialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        firstPage = inflater.inflate(R.layout.india_activity_first_view_page_layout_fragment, container, false);
        unbinder = ButterKnife.bind(this, firstPage);
        mIndia_JujueLine.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //下划线
        mIndia_JujueLine.getPaint().setAntiAlias(true);//抗锯齿
        refresh.setProgressBackgroundColorSchemeResource(android.R.color.white);
        refresh.setColorSchemeResources(R.color.theme);
        refresh.setRefreshing(false);
        refresh.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                    }
                }, 1000);
            }
        });
        refresh.post(new Runnable() {
            @Override
            public void run() {
                refresh.setRefreshing(false);
            }
        });
        tool = new LocationTool(this, getActivity());
        new RxPermissions(getActivity())
                .request(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .compose(new SchedulerTransformer<>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        tool.startLocation();
                    } else {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
        get_Jump_Service();

        return firstPage;
    }

    private String orderno="";
    /**
     * 修改银行卡弹窗事件回调
     */
    IndiaDealDialogInterface mDealDialogInterface =new IndiaDealDialogInterface() {
        @Override
        public void doPlay() {
            Intent auth = new Intent(getContext(), IndiaBankInfoActivity.class);
            auth.putExtra("orderno",orderno);
            startActivity(auth);
        }

        @Override
        public void choose() {

        }
    };


    @Override
    public void onResume() {
        super.onResume();
        loading.show();
        init();
    }

    //跳转到whatsapp
    public void chatIn_Jump_WhatsApp(Context mContext, String mobileNum) {
        try {
            final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=" + mobileNum));
            intent.setPackage("com.whatsapp");
            mContext.startActivity(intent);
        } catch (Exception e) { //  没有安装WhatsApp 跳转google商店
            launch_Jump_AppDetail("com.whatsapp", "com.android.vending");
            e.printStackTrace();
        }
    }

    /**
     * 启动到应用商店app详情界面
     *
     * @param appPkg    目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public void launch_Jump_AppDetail(String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;

            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getActivity().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "Failed to jump", Toast.LENGTH_SHORT).show();
            //如果这里跳转谷歌商品遇到异常  并且 下载链接地址不为空 就跳转下载链接地址
        }
    }


    @OnClick({R.id.first_bottom, R.id.fangkuanhou_bottmom, R.id.jujue_bottom
            , R.id.jujue_vip, R.id.jujuegg_botton})
    public void onViewClicked(View view) {
        Intent web = new Intent(getContext(), IndiaWebViewActivity.class);
        web.putExtra("web", webUrl);
        web.putExtra("type", status);//拒绝后跳转的H5
        web.putExtra("orderno", orderNo);
        switch (view.getId()) {
            case R.id.first_bottom:
                if (MyPreferencesManager.getLogin()) {
                    getLoan_Jump_Count();
//                    switch (authStatus) {
//                        case 1:
//                            getLoan_Jump_Count();
//                            break;
//                        case 2:
//                            Intent bank = new Intent(getContext(), IndiaAddBankActivity.class);
//                            startActivity(bank);
//                            break;
//                        case 3:
//                            Intent auth = new Intent(getContext(), IndiaHomeActivity.class);
//                            startActivity(auth);
//                            break;
//                        default:
//                            Toast.makeText(getActivity(),"Network Exception",Toast.LENGTH_SHORT).show();
//                            break;
//                    }
                } else {
//                    if (TextUtils.isEmpty(MyPreferencesManager.getString("isFirst", ""))) {
//                        dialog = new India_UserNotice_CommonDialog(getContext(), IndiaFirstPageFragment.this);
//                        dialog.show();
//                    } else {
                        Intent login = new Intent(getContext(), IndiaLoginActivity.class);//登陆
                        startActivity(login);
                  //  }
                }
                break;
            case R.id.fangkuanhou_bottmom:
            case R.id.jujue_bottom:
            case R.id.jujue_vip:
                Log.d("loan", "还款 url:" + webUrl);
                Map<String, Object> eventValues1 = new HashMap<>();
                eventValues1.put("product", "product");
                AppsFlyerLib.getInstance().trackEvent(getContext(), "product", eventValues1);
                startActivity(web);

                break;
            case R.id.jujuegg_botton:
                /*Log.d("loan", "还款 url:" + webUrl);
                Map<String, Object> eventValues1 = new HashMap<>();
                eventValues1.put("product", "product");
                AppsFlyerLib.getInstance().trackEvent(getContext(), "product", eventValues1);
                startActivity(web);*/

                //申请贷款再被拒绝后 点击更多按钮 使用系统默认的浏览器 跳转到H5 页面 ，使用webview 无法拉起谷歌商店app
                if (!TextUtils.isEmpty(webUrl)) {
                    String url = webUrl + "?AppName=gg";
                    try {
                        Uri uri = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    /**
     * 判断状态
     */
    public void init() {
        getData_Jump_OnLogin();
        if (MyPreferencesManager.getLogin()) {
            get_Jump_MessageInfo();

        } else {
            mIndia_FirstJoinCard.setVisibility(View.VISIBLE);
            mIndia_FangkuanCard.setVisibility(View.GONE);
            mIndia_ShenhezhongCard.setVisibility(View.GONE);
            mIndia_ShenhejujueCard.setVisibility(View.GONE);
            mIndia_JujueggCard.setVisibility(View.GONE);
            mIndia_ShenhetongguoCard.setVisibility(View.GONE);
            mIndia_DengdaiCard.setVisibility(View.GONE);
            updateBackGround();
        }

    }

    private void updateBackGround(){
        if (mIndia_FirstJoinCard.getVisibility()==View.VISIBLE){
            refresh.setBackgroundColor(0xFFFFFFFF);
        }else {
            refresh.setBackgroundColor(0xFFF7F7F7);
        }
    }

    /**
     * 未登陆状态
     */
    public void getData_Jump_OnLogin() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getData = api.getOnLoginData();
        getData.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.isSuccessful()) {
                        India_UnLogin_Home_ListBean bean = new Gson().fromJson(response.body(), India_UnLogin_Home_ListBean.class);
                        if (bean.getCode() == 200) {
                            //quota.setText(FormatTosepara.formatTosepara(Integer.parseInt(bean.getData().getAmount_limit())));
                            quota.setText(bean.getData().getAmount_limit());
                            String[] addr = bean.getData().getTop_desc_fq().split("\\*");
                            MyPreferencesManager.putInt("authority", bean.getData().getAuthority());
                        } else {
                            MyToast.show(getContext(), getContext().getResources().getString(R.string.india_jiekoucuo_wu));
                        }
                    }
                } catch (Exception e) {

                }
                refresh.setRefreshing(false);
                mIndia_NestedScroll.setVisibility(View.VISIBLE);
                if (!MyPreferencesManager.getLogin()) {
                    loading.dismiss();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                MyToast.show(getContext(), getContext().getResources().getString(R.string.india_jianchawang_luo));
                refresh.setRefreshing(false);
                mIndia_NestedScroll.setVisibility(View.VISIBLE);
                loading.dismiss();
            }
        });
    }

    private String getDateToString(long time) {
        Date d = new Date(time*1000);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(d);
    }

    /**
     * 登陆后请求数据
     */
    public void getData_Jump_Login() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getData = api.getLoginData(MyPreferencesManager.getString("token", ""), MyApplication.source);
        getData.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.isSuccessful()) {
                        India_User_LoginList_Home_Bean bean = new Gson().fromJson(response.body(), India_User_LoginList_Home_Bean.class);
                        //Log.e("data","==========w===="+response.body());
                        if (bean.getCode() == 200) {

                            if(bean.getData()==null){
                                //订单为空 个人信息修改银行卡页面不显示
                                orderno="";
                                INdia_Update_CardInfoListBean INdiaUpdateCardInfoListBean = new INdia_Update_CardInfoListBean();
                                INdiaUpdateCardInfoListBean.setCode(500);
                                INdiaUpdateCardInfoListBean.setOrderno("");//订单编号
                                EventBus.getDefault().post(INdiaUpdateCardInfoListBean);
                            }

                            if (null != bean.getData()) {

                                //发送消息到 MinePageFragment 里面做逻辑处理
                                INdia_Update_CardInfoListBean INdiaUpdateCardInfoListBean = new INdia_Update_CardInfoListBean();
                                INdiaUpdateCardInfoListBean.setCode(200);
                                INdiaUpdateCardInfoListBean.setOrderno(bean.getData().getOrderno());//订单编号
                                EventBus.getDefault().post(INdiaUpdateCardInfoListBean);

                                orderno=bean.getData().getOrderno();

                                if(bean.getData().getModify_bank()==1){
                                    //修改银行卡弹窗 ==1  需要修改银行卡 弹出弹窗
                                    if(updateBankNumberDialog==null){
                                        updateBankNumberDialog=new India_Update_BankNumber_Dialog(getContext(), mDealDialogInterface);
                                    }
                                    updateBankNumberDialog.show();
                                }

                                mIndia_FirstJoinCard.setVisibility(View.GONE);
                                mIndia_FangkuanCard.setVisibility(View.GONE);
                                mIndia_ShenhezhongCard.setVisibility(View.GONE);
                                mIndia_ShenhejujueCard.setVisibility(View.GONE);
                                mIndia_JujueggCard.setVisibility(View.GONE);
                                mIndia_ShenhetongguoCard.setVisibility(View.GONE);
                                mIndia_DengdaiCard.setVisibility(View.GONE);
                                updateBackGround();
                                //2021-6-12改 字体颜色不对
                                //fangkuanhouDate.setTextColor(getResources().getColor(R.color.theme));

                                //2021-6-12改
                                // fangkuanhouBottmom.setBackgroundResource(R.drawable.india_button_jump_sure);
                                mIndia_FangkuanhouBottmom.setBackgroundResource(R.drawable.theme_25r);
//                                headLinear.setBackgroundColor(getResources().getColor(R.color.theme));

                                //2021-6-12改 字体颜色不对
                                // fangkuanhouQuota.setTextColor(getResources().getColor(R.color.theme));


                                MainActivity.isShow = true;
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                orderNo = bean.getData().getOrderno();

                                //-------------先设置成以前的默认值 再根据下面的状态 改变 文案
                                // tv_cons.setText("Al confirmar, acepta el Acuerdo de préstamo de.");

                                //显示优惠卷
                                if (bean.getData().isCoupon()) {
                                    show_Jump_CouponDialog(bean.getData().getCoupon_amount());
                                }

                                //显示不同的状态
                                //"status": 0, //0-待审核，1-通过，2-拒绝，4-已放款，5-已逾期，7-延期
                                //"checkstatus": 0, //0-机审拒绝，1-机审通过，2-无需审核
                                //Log.e("data",bean.getData().toString());
                                //int is_reloan;//0 是新增 1是复借
                                //注意 is_reloan 如果审核失败 is_reloan 也是 0  不能单独作为逻辑来判断

                                if (bean.getData().getStatus() == 4 && bean.getData().getIs_reloan() == 0) {
                                    //表示已经放款了 需要进行统计 为了防止 每次进入这个页面 重复统计 根据订单ID 进行判断
                                    String orderID = MyPreferencesManager.getOrderID();
                                    if (!String.valueOf(bean.getData().getId()).equals(orderID)) {
                                        //这里视为完成申请贷款的条件 多次贷款就统计多次
                                        IndiaAdjust_Helper.completeApplicationLoan();
                                        //这里基本认为是首次统计 还需要进行下面的逻辑判断
                                        try {
                                            String tagName = getContext().getPackageName() + ".firstLoan";//需要创建的文件名
                                            File destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), tagName + ".txt");
                                            if (!destFile.exists()) {
                                                //认为是首次放款成功的
                                                IndiaAdjust_Helper.firstLoan();
                                                //首次客户 往sdcard文件夹下写入一个txt文件
                                                try {
                                                    India_FileApp_InstallUtil fileAppInstallUtil = new India_FileApp_InstallUtil();
                                                    fileAppInstallUtil.saveTextFile(getContext(), DeviceIdUtil.getUUIDInstall(), tagName);
                                                    Log.e("data", "First loan");
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            } else {
                                                Log.e("data", "Not First loan");
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    //统计完成把orderID 缓存起来 用于下次进入判断  下次进入拿到的orderID 和 服务器接口一样 就不统计
                                    MyPreferencesManager.putOrderID(String.valueOf(bean.getData().getId()));
                                }

                                Log.e("zhujia","---status"+bean.getData().getStatus());
                                switch (bean.getData().getStatus()) {
                                    case 0: //审核中
                                        if (bean.getData().getCheckstatus() == 0) {
                                            mIndia_JujueggCard.setVisibility(View.VISIBLE);
                                            status = 1;
                                        } else if (bean.getData().getCheckstatus() == 1) {
                                            try {
                                                mDay = bean.getData().getDays() + "";
                                                mDaozhang = bean.getData().getDamount() + "";//到账金额
                                                mDamount = bean.getData().getDamount();//到账金额
                                                mAllMount = bean.getData().getAmount();//贷款金额
                                                mZongshu = bean.getData().getPay_amount() + "";//还款金额

                                                mFuwu = bean.getData().getService_fee() + "";

                                                mLixi = bean.getData().getInterestrate();

                                                commit = bean.getData().getConfirmstatus();

                                                mPayAmount = bean.getData().getPay_amount();
                                                //1:确认 confirmstatus  0:未确认
                                                try {
                                                    mIndia_ShenhetongguoCard.setVisibility(View.VISIBLE);
                                                    shenghetongguo_amount.setText("$ " + bean.getData().getAmount());
                                                    shenghetongguo_damount.setText("$ " + bean.getData().getDamount());
                                                    try {
                                                        shenghetongguo_date.setText(getDateToString(Long.valueOf(bean.getData().getDeadline()*1000)));
                                                        double amout = Double.valueOf(bean.getData().getAmount());
                                                        double lilv = Double.valueOf(bean.getData().getInterestrate());
                                                        BigDecimal decimalAmout = new BigDecimal(amout);
                                                        BigDecimal decimalLilv = new BigDecimal(lilv);
                                                        BigDecimal decimal16 = new BigDecimal(0.16);
                                                        BigDecimal decimal54 = new BigDecimal(0.54);
                                                        BigDecimal decimal30 = new BigDecimal(0.30);
                                                        shenghetongguo_shuifei.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal16).multiply(decimal30).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                        shenghetongguo_yongjin.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal54).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                        shenghetongguo_lilv.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal30).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                    }catch (Exception e){
                                                    }
                                                } catch (Exception e) {

                                                }
                                            } catch (Exception e) {

                                            }
                                        } else {
                                            mIndia_ShenhezhongCard.setVisibility(View.VISIBLE);
                                        }
                                        break;
                                    case 1://审核后
                                        try {
// 延期
                                            mIndia_ShenhetongguoCard.setVisibility(View.VISIBLE);
                                            shenghetongguo_amount.setText("$ " + bean.getData().getAmount());
                                            shenghetongguo_damount.setText("$ " + bean.getData().getDamount());
                                            try {
                                                shenghetongguo_date.setText(getDateToString(Long.valueOf(bean.getData().getDeadline()*1000)));
                                                double amout = Double.valueOf(bean.getData().getAmount());
                                                double lilv = Double.valueOf(bean.getData().getInterestrate());
                                                BigDecimal decimalAmout = new BigDecimal(amout);
                                                BigDecimal decimalLilv = new BigDecimal(lilv);
                                                BigDecimal decimal16 = new BigDecimal(0.16);
                                                BigDecimal decimal54 = new BigDecimal(0.54);
                                                BigDecimal decimal30 = new BigDecimal(0.30);
                                                Log.e("zhujia","---amout---"+amout);
                                                Log.e("zhujia","---amout--1-"+decimalAmout.multiply(decimalLilv).multiply(decimal16).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                shenghetongguo_shuifei.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal16).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                shenghetongguo_yongjin.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal54).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                shenghetongguo_lilv.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal30).setScale(2,BigDecimal.ROUND_HALF_UP));
                                            }catch (Exception e){
                                            }
                                        } catch (Exception e) {

                                        }
                                        break;
                                    case 2://已拒绝
                                        mIndia_JujueggCard.setVisibility(View.VISIBLE);
                                        status = 1;
                                        break;
                                    case 4://已放款
                                    case 7:
                                        // 延期
                                        mIndia_FangkuanCard.setVisibility(View.VISIBLE);
                                        huankuan_amount.setText("$ " + bean.getData().getAmount());
                                        huankuan_damount.setText("$ " + bean.getData().getDamount());
                                        mIndia_FangkuanhouQuota.setText("$ " + bean.getData().getPay_amount());
                                        try {
                                            mIndia_FangkuanhouDate.setText(getDateToString(Long.valueOf(bean.getData().getDeadline())));
                                            double amout = Double.valueOf(bean.getData().getAmount());
                                            double lilv = Double.valueOf(bean.getData().getInterestrate());
                                            BigDecimal decimalAmout = new BigDecimal(amout);
                                            BigDecimal decimalLilv = new BigDecimal(lilv);
                                            BigDecimal decimal16 = new BigDecimal(1.6);
                                            BigDecimal decimal54 = new BigDecimal(0.54);
                                            huankuan_shuifei.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal16).setScale(2,BigDecimal.ROUND_HALF_UP));
                                            huankuan_yongjin.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal54).setScale(2,BigDecimal.ROUND_HALF_UP));
                                            huankuan_lilv.setText("$ " + decimalAmout.multiply(decimalLilv).setScale(2,BigDecimal.ROUND_HALF_UP));
                                        }catch (Exception e){
                                        }
                                        status = 2;
                                        break;
                                    case 5:
                                        // 已逾期
                                        mIndia_FangkuanCard.setVisibility(View.VISIBLE);
                                        huankuan_amount.setText("$ " + bean.getData().getAmount());
                                        huankuan_damount.setText("$ " + bean.getData().getDamount());
                                        mIndia_FangkuanhouQuota.setText("$ " + bean.getData().getPay_amount());
                                        try {
                                            mIndia_FangkuanhouDate.setText(getDateToString(Long.valueOf(bean.getData().getDeadline())));
                                            double amout = Double.valueOf(bean.getData().getAmount());
                                            double lilv = Double.valueOf(bean.getData().getInterestrate());
                                            BigDecimal decimalAmout = new BigDecimal(amout);
                                            BigDecimal decimalLilv = new BigDecimal(lilv);
                                            BigDecimal decimal16 = new BigDecimal(0.16);
                                            BigDecimal decimal54 = new BigDecimal(0.54);
                                            huankuan_shuifei.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal16).setScale(2,BigDecimal.ROUND_HALF_UP));
                                            huankuan_yongjin.setText("$ " + decimalAmout.multiply(decimalLilv).multiply(decimal54).setScale(2,BigDecimal.ROUND_HALF_UP));
                                            huankuan_lilv.setText("$ " + decimalAmout.multiply(decimalLilv).setScale(2,BigDecimal.ROUND_HALF_UP));
                                        }catch (Exception e){
                                        }
                                        mIndia_FangkuanhouQuota.setTextColor(getResources().getColor(R.color.yuqi));
                                        mIndia_FangkuanhouBottmom.setBackgroundResource(R.drawable.theme_25r);
                                        status = 2;
                                        break;
                                }
                            } else {
                                MainActivity.isShow = false;
                                mIndia_FirstJoinCard.setVisibility(View.VISIBLE);
                                mIndia_FangkuanCard.setVisibility(View.GONE);
                                mIndia_ShenhezhongCard.setVisibility(View.GONE);
                                mIndia_ShenhejujueCard.setVisibility(View.GONE);
                                mIndia_JujueggCard.setVisibility(View.GONE);
                                mIndia_ShenhetongguoCard.setVisibility(View.GONE);
                                mIndia_DengdaiCard.setVisibility(View.GONE);
                                updateBackGround();
                            }

                        } else if (bean.getCode() == 401) {
                            MyPreferencesManager.putString("token", "");
                            MyPreferencesManager.putLogin(false);
                            MainActivity.isShow=false;
                            Intent intent = new Intent(getContext(), IndiaLoginActivity.class);
                            startActivity(intent);
                        } else {
                            MyToast.show(getContext(), getContext().getResources().getString(R.string.india_jiekoucuo_wu));
                        }
                        loading.dismiss();
                    }else {
                        loading.dismiss();
                    }
                    get_Jump_Html();
                } catch (Exception e) {
                    loading.dismiss();
                }
                refresh.setRefreshing(false);
                mIndia_NestedScroll.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                MyToast.show(getContext(), getContext().getResources().getString(R.string.india_jianchawang_luo));
                refresh.setRefreshing(false);
                mIndia_NestedScroll.setVisibility(View.VISIBLE);
            }
        });
    }

    public void getLoan_Jump_Count() {
        loading.show();
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getLoan = api.getLoanCount(MyPreferencesManager.getString("token", ""), MyApplication.source);
        getLoan.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    loading.dismiss();
                    if (response.isSuccessful()) {
                        BaseBean baseBean = new Gson().fromJson(response.body(), BaseBean.class);
                        if (baseBean.getCode() == 200) {
                            //统计开始申请贷款
                            IndiaAdjust_Helper.startApplicationLoan();
                            getData_Jump_Login();
                        } else if (baseBean.getCode() == 401) {
                            MyPreferencesManager.putString("token", "");
                            MyPreferencesManager.putLogin(false);
                            MainActivity.isShow=false;
                            Intent intent = new Intent(getContext(), IndiaLoginActivity.class);
                            startActivity(intent);
                        }
                    }
                } catch (Exception e) {
                    loading.dismiss();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading.dismiss();
            }
        });
    }

    @Override
    public void doPlay() {
        Intent login = new Intent(getContext(), IndiaLoginActivity.class);//登陆
        startActivity(login);
    }

    @Override
    public void choose() {

    }

    @Override
    public void backAdd(String location) {
        this.location = location;
        if (one == -1) {
            init();
            one = 1;
        }
    }

    @Override
    public void onError() {

    }

    @Override
    public void sure() {
        MyPreferencesManager.putLong("date1", new Date().getTime());
    }

    @Override
    public void cancel() {

    }

    //获取身份信息
    public void get_Jump_MessageInfo() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getInfo = api.getMessageInfo(MyPreferencesManager.getString("token", ""), MyApplication.getInstance().source);
        getInfo.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    India_MessageInfo_ListBean infoBean = new Gson().fromJson(response.body(), India_MessageInfo_ListBean.class);
                    if (infoBean.getCode() == 200) {

                        //Log.e("data","======"+infoBean.getData());
                        if (null == infoBean.getData()) {
                            authStatus = 1;
                            getData_Jump_Login();
                        } else {
                            mIndia_FirstJoinCard.setVisibility(View.VISIBLE);
                            mIndia_FangkuanCard.setVisibility(View.GONE);
                            mIndia_ShenhezhongCard.setVisibility(View.GONE);
                            mIndia_ShenhejujueCard.setVisibility(View.GONE);
                            mIndia_JujueggCard.setVisibility(View.GONE);
                            mIndia_ShenhetongguoCard.setVisibility(View.GONE);
                            mIndia_DengdaiCard.setVisibility(View.GONE);
                            updateBackGround();
                            if (infoBean.getData().getWork() == 1 && infoBean.getData().getContacts() == 1
                                    && infoBean.getData().getCominfo() == 1 && infoBean.getData().getOcr() == 1
                                    && infoBean.getData().getBankinfo() == 0) {
                                bank = true;
                                authStatus = 2;
                            } else {
                                authStatus = 3;
                                bank = false;
                            }
                            loading.dismiss();
                        }
                    } else {
                        loading.dismiss();
                    }
                }else {
                    loading.dismiss();
                }
            }
            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading.dismiss();
            }
        });
    }

    public void get_Jump_Service() {
        Log.d("loan", "index getService");
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getService = api.getPhone();
        getService.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("loan", "index getService onResponse:" + response.body());

                if (response.isSuccessful()) {
                    India_User_PhoneList_Bean bean = new Gson().fromJson(response.body(), India_User_PhoneList_Bean.class);
                    if (bean.getCode() == 200) {
                        MyPreferencesManager.putString("email", bean.getData().getE_mail());
                        MyPreferencesManager.putString("phone", bean.getData().getTelephone());

                        //Log.e("data",bean.getData().getTelephone());
                        //Log.e("data",bean.getData().getE_mail());
                    }
//                    MyPreferencesManager.putString("email", bean.getData().getData().getHome_email());
//                    MyPreferencesManager.putString("phone", bean.getData().getData().getHome_phone());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
            }
        });
    }

    public void get_Jump_Html() {
        //Log.e("data","====getHtml=====");
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> html = api.getUrl();
        html.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                //Log.e("data","====url====="+response.body());
                if (response.isSuccessful()) {
                    India_UrlListBean bean = new Gson().fromJson(response.body(), India_UrlListBean.class);
                    if (bean.getCode() == 200) {
                        if (status == 1) {
                            webUrl = bean.getData().getProduct_url();
                        } else {
                            webUrl = bean.getData().getH5pay_url();
                            MyPreferencesManager.putString("payweb", bean.getData().getH5pay_url());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
            }
        });
    }

    private India_User_Coupon_CommonDialog userCouponCommonDialog;

    private void show_Jump_CouponDialog(double coupon) {
        int hasShowedCoupon = MyPreferencesManager.getInt("hasShowedCoupon", 0);
        if (hasShowedCoupon == 0) {
            if (userCouponCommonDialog == null) {
                userCouponCommonDialog = new India_User_Coupon_CommonDialog(getActivity(), new IndiaOnDialogListener() {
                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onConfirm() {
                        //已经显示过coupon
                        MyPreferencesManager.putInt("hasShowedCoupon", 1);
                    }
                }, coupon);
            }
            userCouponCommonDialog.show();
        }
    }
}
